/******************************************************************************************

Made by Flashphoner. All rights reserved.
These sources can only be used for working with Flashphoner server.
If you want use this to create your own application (separate from Flashphoner server)
please contact support@flashphoner.com 

******************************************************************************************/

package com.flashphoner.app;

import com.flashphoner.sdk.rtmp.IRtmpClientsCollection;
import com.flashphoner.sdk.rtmp.IRtmpClient;

import com.wowza.wms.logging.WMSLogger;
import com.wowza.wms.logging.WMSLoggerFactory;
import com.wowza.wms.client.IClient;

import java.util.*;

public class RtmpClients implements IRtmpClientsCollection {

    private static WMSLogger log = WMSLoggerFactory.getLogger(RtmpClients.class);

    private static IRtmpClientsCollection rtmpClientsCollection;

    private Map<IClient, IRtmpClient> rtmpClients = Collections.synchronizedMap(new HashMap<IClient, IRtmpClient>());

    private RtmpClients() {

    }

    public static IRtmpClientsCollection getInstance() {
        if (rtmpClientsCollection == null) {
            rtmpClientsCollection = new RtmpClients();
        }
        return rtmpClientsCollection;
    }

    public IRtmpClient findByLogin(String login) {
        Iterator it = rtmpClients.keySet().iterator();
        synchronized (rtmpClients) {
            while (it.hasNext()) {
                IRtmpClient rtmpClient = rtmpClients.get(it.next());
                if (rtmpClient.getLogin().equals(login)) {
                    return rtmpClient;
                }
            }
        }
        return null;
    }

    public void add(IRtmpClient rtmpClient) {
        synchronized (rtmpClients) {
            rtmpClients.put(rtmpClient.getClient(), rtmpClient);
        }
    }

    public IRtmpClient remove(IRtmpClient rtmpClient) {
        synchronized (rtmpClients) {
            return rtmpClients.remove(rtmpClient.getClient());
        }
    }

    public IRtmpClient findByClient(IClient client) {
        synchronized (rtmpClients) {
            return rtmpClients.get(client);
        }
    }
}
